package sapling.service;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import sapling.dao.AdminDao;
import sapling.dao.RoleDao;
import sapling.form.AdminForm;
import sapling.model.Admin;
import sapling.model.Company;
import sapling.model.Role;
import sapling.utils.Md5Util;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * Created by Administrator on 2017/6/21.
 */
@Service
@Transactional
public class AdminService {

    @Autowired
    private AdminDao adminDao;

    @Autowired
    private RoleDao roleDao;
    /**
     * 添加用户
     * @param form
     */
    public void save(AdminForm form) {
        Subject currentUser = SecurityUtils.getSubject();
        String username = currentUser.getSession().getAttribute("username").toString();
        Admin admins=adminDao.findOneByUsername(username);
        if(Objects.nonNull(admins)){
            Admin admin=new Admin();
            admin.setUsername(form.getUsername());
            admin.setPassword(Md5Util.getMd5(form.getPassword()));
            admin.setCompany(admins.getCompany());
            Role role= roleDao.findOneByName("common");
            List<Role> roleList = new ArrayList<>();
            roleList.add(role);
            admin.setRoleList(roleList);
            adminDao.save(admin);
        }

    }

    /**
     * 修改密码
     * @param form
     */
    public void passwordSave(AdminForm form) {
        Subject currentUser = SecurityUtils.getSubject();
        String username = currentUser.getSession().getAttribute("username").toString();
        Admin admin= adminDao.findOneByUsername(username);
        if(Objects.nonNull(admin)){
            admin.setPassword(Md5Util.getMd5(form.getPassword()));
            adminDao.save(admin);
        }
    }
}
